<?php
/**
* Interface form for placing/modifying/viewing a reservation
* This file will present a form for a user to
*  make a new reservation or modify/delete an old one.
* It will also allow other users to view this reservation.
* @author Nick Korbel <lqqkout13@users.sourceforge.net>
* @author David Poole <David.Poole@fccc.edu>
* @version 02-07-09
* @package phpScheduleIt
*
* Copyright (C) 2003 - 2007 phpScheduleIt & 2010 ITOxygen
* License: GPL, see LICENSE
*/

include_once('lib/Resource.class.php');
include_once('lib/AdditionalResource.class.php');
include_once('lib/Template.class.php');
include_once('lib/helpers/ReservationHelper.class.php');
include_once('lib/Utility.class.php');

$timer = new Timer();
$timer->start();

$is_blackout = (isset($_GET['is_blackout']) && ($_GET['is_blackout'] == '1'));

if ($is_blackout) {
	// Make sure user is logged in
	if (!Auth::is_logged_in()) {
		Auth::print_login_msg();
	}

	include_once('lib/Blackout.class.php');
	$Class = 'Blackout';
	$_POST['minres'] = $_POST['maxRes'] = null;
}
else {

	include_once('lib/Reservation.class.php');
	$Class = 'Reservation';
}

if ((!isset($_GET['read_only']) || !$_GET['read_only']) && $conf['app']['readOnlyDetails']) {
	// Make sure user is logged in
	if (!Auth::is_logged_in()) {
		Auth::print_login_msg();
	}
}

$t = new Template();

if (isset($_POST['btnSubmit']) && strstr($_SERVER['HTTP_REFERER'], $_SERVER['PHP_SELF'])) {
	$t->set_title(translate("Processing $Class"));
	$t->printHTMLHeader();
	$t->startMain();
 	process_reservation($_POST['fn']);
}
else {
	$res_info = getResInfo();
	$t->set_title($res_info['title']);
    $t->printHTMLHeader();
    $t->startMain();
    present_reservation($res_info['resid']);
}

// End main table
$t->endMain();

$timer->stop();
$timer->print_comment();

// Print HTML footer
$t->printHTMLFooter();

/**
* Processes a reservation request (add/del/edit)
* @param string $fn function to perform
*/
function process_reservation($fn) 
{

	$success = false;
	global $Class;
	$is_pending = (isset($_POST['pending']) && $_POST['pending']);

	if (isset($_POST['start_date'])) // Parse the POST-ed starting and ending dates
	{			
		$sd = explode(INTERNAL_DATE_SEPERATOR, $_POST['start_date']);
		$ed = explode(INTERNAL_DATE_SEPERATOR, $_POST['end_date']);

		$start_date = mktime(0,0,0, $sd[0], $sd[1], $sd[2]);
		$end_date = mktime(0,0,0, $ed[0], $ed[1], $ed[2]);
	}

	if (isset($_POST['resid']))
	{
		$res = new $Class($_POST['resid'], false, $is_pending);
	}
	else if (isset($_GET['resid']))
	{
		$res = new $Class($_GET['resid'], false, $is_pending);
	}
	else 
	{
		// New reservation
		$res = new $Class(null, false, $is_pending);
		if ($_POST['interval'] != 'none') // Check for reservation repeation
		{		
			if ($start_date == $end_date) 
			{
				$res->is_repeat = true;
				$days = isset($_POST['repeat_day']) ? $_POST['repeat_day'] : NULL;
				$week_num = isset($_POST['week_number']) ? $_POST['week_number'] : NULL;
				$repeat = CmnFns::get_repeat_dates($start_date, $_POST['interval'], $days, $_POST['repeat_until'], $_POST['frequency'], $week_num);
			}
			else 
			{
				// Cannot repeat multi-day reservations
				$repeat = array($start_date);
				$res->is_repeat = false;
			}
		}
		
		else 
		{
			$repeat = array($start_date);
			$res->is_repeat = false;
		}
	  if ($_POST['random_dates']) {
      $dates_add = explode(",", substr($_POST['random_dates'], 0, -1));  //process manually selected dates
      if (count($dates_add) > 0) {
          $res->is_repeat = true;
          for ($i = 0; $i < count($dates_add); $i++) {
             list($repeat_m, $repeat_d, $repeat_y) = explode('/', $dates_add[$i]);
	 	         $repeat[] = mktime(0,0,0,$repeat_m, $repeat_d, $repeat_y);
             
          }
      }
     }     
  	$repeat = array_unique($repeat);                //remove any duplicate dates added through 'add random dates'
    $repeat = array_values($repeat);                //reindex array in case indexes aren't linear
    if (count($repeat) == 1) {                      //if only one date exists, not recurring anymore
      $res->is_repeat = false;
    }
  }

 

 
	$cur_user = new User(Auth::getCurrentID());
	$res->adminMode = Auth::isAdmin() || $cur_user->get_isadmin() || ($fn != 'create' && $cur_user->is_group_admin($res->user->get_groupids()));

  //$title = isset($_POST['title']) ? stripslashes(htmlspecialchars($_POST['title'])) : '';
  if (isset($_POST['title'])) 
  {
  $title = (strcmp($_POST['title'], "custom") == 0) ? stripslashes(htmlspecialchars($_POST['title2'])) : stripslashes(htmlspecialchars($_POST['title']));
	}
  
  
  
  if (Auth::isAdmin() || $cur_user->get_isadmin())
	{
		$res->is_pending = false;	
	}
	
	if ($fn == 'create' || $fn == 'modify') 
	{
		$helper = new ReservationHelper();
		$util = new Utility();
    
    
		$orig = (isset($_POST['orig_invited_users']) && count($_POST['orig_invited_users']) > 0) ? $_POST['orig_invited_users'] : array();
		
    
    $invited = (isset($_POST['invited_users'])) ? $_POST['invited_users'] : array();
		$removed = (isset($_POST['removed_users'])) ? $_POST['removed_users'] : array();

		$users_to_remove = $helper->getRowsForRemoval($orig, $removed, $invited);
		$users_to_invite = $helper->getRowsForInvitation($orig, $invited);
		
		
		$unchanged = $helper->getUnchangedUsers($orig, $invited);       //Fixed - now adds participating users to list of users to email for modifications
    if (isset($_POST['participating_users']) && count ($_POST['participating_users']) > 0) {
      $unchanged_temp = $_POST['participating_users'];
      foreach($unchanged_temp as $idx => $val) {
				$parts = explode('|', $val);
				$unchanged_temp2[$parts[0]] = $parts[1];
			}
		$unchanged_users = array_merge($unchanged, $unchanged_temp2);	
    }
    else {
    $unchanged_users = $unchanged;
    }

		$orig_resources = (isset($_POST['orig_resources']) && count($_POST['orig_resources']) > 0) ? $_POST['orig_resources'] : array();
		$selected_resources =  (isset($_POST['selected_resources']) && count($_POST['selected_resources']) > 0) ? $_POST['selected_resources'] : array();

		$resources_to_add = $util->getAddedItems($orig_resources, $selected_resources);
		$resources_to_remove = $util->getRemovedItems($orig_resources, $selected_resources);
    $recur_summary = isset($_POST['recursummary']) ? stripslashes(htmlspecialchars($_POST['recursummary'])) : '';
    $nonuptninfo = isset($_POST['nonuptninfo']) ? stripslashes(htmlspecialchars($_POST['nonuptninfo'])) : '';
    

		$res->user 		= new User($_POST['memberid']);
		$res->start_date= $start_date;
		$res->end_date 	= $end_date;
		$res->start		= $_POST['starttime'];
		$res->end		= $_POST['endtime'];
    $res->requestorid = $_POST['requestorid'];
    $res->standing = isset($_POST['standing']);
    $res->recur_summary = $recur_summary;
    $res->nonuptninfo = $nonuptninfo;
    
    $res->startdatereport = date("Y-m-d", $res->start_date);
       
	 // $res->summary	= stripslashes(htmlspecialchars($_POST['summary'], ENT_NOQUOTES));
		$res->summary = str_replace('"',"'",$_POST['summary']);
  //  $res->summary = htmlentities($_POST['summary'], ENT_QUOTES);
    
    $res->allow_participation = (int)!isset($_POST['allow_participation']);
		$res->allow_anon_participation = 0;
		$res->link 		= $_POST['link'];
		$res->meetingtype  = $_POST['meetingtype'];
		$res->title = $title;
		$res->department = $_POST['department'];
    $res->reminderid = isset($_POST['reminderid']) ? $_POST['reminderid'] : null;
		$res->reminder_minutes_prior = isset($_POST['reminder_minutes_prior']) ? intval($_POST['reminder_minutes_prior']) : 0;
	  $res->status = isset($_POST['status']) ? $_POST['status'] : 'PENDING';
	  $res->billable = isset($_POST['billable']);
    $res->origstartdate = $_POST['origstartdate'];
    $res->origenddate = $_POST['origenddate'];
    $res->origstarttime = $_POST['origstarttime'];
    $res->origendtime = $_POST['origendtime'];
    $res->presenter = isset($_POST['presenter']) ? $_POST['presenter'] : '';
    $res->practitioner = isset($_POST['practitioner']) ? $_POST['practitioner'] : '';
    $res->patient = isset($_POST['patient']) ? $_POST['patient'] : '';
    $res->birthyear = isset($_POST['birthyear']) ? $_POST['birthyear'] : '';
    $res->insurance = isset($_POST['insurance']) ? $_POST['insurance'] : '';
    $res->mileage = isset($_POST['mileage']) ? $_POST['mileage'] : '';
    $res->specialty = isset($_POST['specialty']) ? $_POST['specialty'] : '';
    $res->subspecialty = isset($_POST['subspecialty']) ? $_POST['subspecialty'] : '';
    $res->reschedule = isset($_POST['reschedule']);
    $res->rescheduledate = isset($_POST['rescheduledate']) ? $_POST['rescheduledate'] : '';
    $res->telemedicine = isset($_POST['telemedicine']);
  }
 	
 	if ($fn == 'create') 
	{
		$sitecoords = array();                // automatically add site coordinators to invited users list
    for ($i = 0; $i < count($resources_to_add); $i++) {
      $resource = new AdditionalResource($resources_to_add[$i]);
      $tmpuser = new User($resource->get_sitecoord_id());
      if (($resource->get_sitecoord_id() != Auth::getCurrentID()) && ($resource->get_sitecoord_id() != $res->user->get_id())) {
        if ($tmpuser->get_email()) 
        $sitecoords[$resource->get_sitecoord_id()] = $tmpuser->get_email();
      }
    }
    
    $users_to_invite = array_merge($users_to_invite, $sitecoords);	
 		
    
    $res->resource = new Resource($_POST['machid']);
		$res->scheduleid= $_POST['scheduleid'];
		$res->repeat = $repeat;
		$res->add_res($users_to_invite, $resources_to_add);
	}
	else if ($fn == 'modify') 
	{
		 $sitecoords = array();                // automatically add site coordinators to invited users list
    for ($i = 0; $i < count($resources_to_add); $i++) {
      $resource = new AdditionalResource($resources_to_add[$i]);
      $tmpuser = new User($resource->get_sitecoord_id());          // site coordinator user
   
      $users = $res->db->get_res_users($res->get_id());            // get all users in reservation
  
      $is_invited = false;
       foreach  ($users as $key => $value) {
          if ($users[$key]['memberid'] == $resource->get_sitecoord_id()) {
            $is_invited = true;
          }
       }       
      //   if (($resource->get_sitecoord_id() != Auth::getCurrentID()) && ($resource->get_sitecoord_id() != $res->user->get_id())) {
      
          if ((!$is_invited) && ($resource->get_sitecoord_id() != $res->user->get_id())) {
            if ($tmpuser->get_email()) 
              $sitecoords[$resource->get_sitecoord_id()] = $tmpuser->get_email();
          }
      
    }
   
  $users_to_invite = array_merge($users_to_invite, $sitecoords);	
 	
 	
 	
 	$sitecoordsdel = array();
    for ($i = 0; $i < count($resources_to_remove); $i++) {
      $resource = new AdditionalResource($resources_to_remove[$i]);
      $tmpuser = new User($resource->get_sitecoord_id());     
      if ($res->user->get_id() != $resource->get_sitecoord_id()) {  //don't remove meeting creator
        $sitecoordsdel[$resource->get_sitecoord_id()] = $tmpuser->get_email();
      }
    }
 	
 	$users_to_remove = array_merge($users_to_remove, $sitecoordsdel);	
    $res->summary = str_replace("\n", '', $_POST['summary']);
		$res->mod_res($users_to_invite, $users_to_remove, $unchanged_users, $resources_to_add, $resources_to_remove, isset($_POST['del']), isset($_POST['mod_recur']));
	}
	else if ($fn == 'delete') 
	{
		$res->del_res(isset($_POST['mod_recur']));
	}
	else if ($fn == 'approve') 
	{
		$res->approve_res(isset($_POST['mod_recur']));
	}
	 
	 if ($fn == 'view') 
	{
		$res->status = isset($_POST['status']) ? $_POST['status'] : 'PENDING';
    $res->origstartdate = $_POST['origstartdate'];
    $res->origenddate = $_POST['origenddate'];
    $res->origstarttime = $_POST['origstarttime'];
    $res->origendtime = $_POST['origendtime'];
    $helper = new ReservationHelper();
		$util = new Utility();
    
		$orig_resources = (isset($_POST['orig_resources']) && count($_POST['orig_resources']) > 0) ? $_POST['orig_resources'] : array();
		$selected_resources =  (isset($_POST['selected_resources']) && count($_POST['selected_resources']) > 0) ? $_POST['selected_resources'] : array();
    $all_resources =  (isset($_POST['all_resources']) && count($_POST['all_resources']) > 0) ? $_POST['all_resources'] : array();

		$resources_to_add = $util->getAddedItems($orig_resources, $selected_resources);
	  $resources_to_remove = $util->getRemovedItems($orig_resources, $selected_resources);
  
    $mod_recur = (isset($_POST['is_recur']));
   
    
    $resourcecount = count($resources_to_remove);
    for ($i = 0; $i < $resourcecount; $i++) {
      $resourcetemp = new AdditionalResource($resources_to_remove[$i]);
         
      if ($resourcetemp->get_sitecoord_id() != $cur_user->get_id()) {
        unset($resources_to_remove[$i]);
        }
    }
    
    $sitecoords = array();                // automatically add site coordinators to invited users list
        
    for ($i = 0; $i < count($resources_to_add); $i++) {
      $resource = new AdditionalResource($resources_to_add[$i]);
      $tmpuser = new User($resource->get_sitecoord_id());
      $users = $res->db->get_res_users($res->get_id());
  
      $is_invited = false;
       foreach  ($users as $key => $value) {
          if ($users[$key]['memberid'] == Auth::getCurrentID()) {
            $is_invited = true;
          }
       }
      
      if ((!$is_invited) && ($resource->get_sitecoord_id() != $res->user->get_id())) {
        if ($tmpuser->get_email()) 
        $sitecoords[$resource->get_sitecoord_id()] = $tmpuser->get_email();
      }
    }
   
    $users_to_invite = $sitecoords;	
 	
 	  	
 	  $sitecoordsdel = array();
      foreach ($resources_to_remove as $key => $val) {
        $resource = new AdditionalResource($val);
        $tmpuser = new User($resource->get_sitecoord_id());
        if ($res->user->get_id() != $resource->get_sitecoord_id()) {   //don't remove meeting creator
          $sitecoordsdel[$resource->get_sitecoord_id()] = $tmpuser->get_email();
        }
      }
 	
 	  $users_to_remove = $sitecoordsdel;	
        
    $res->mod_res_resource($users_to_invite, $resources_to_add, $resources_to_remove, $mod_recur, $cur_user);
    
	}
}

/**
* Prints out reservation info depending on what parameters
*  were passed in through the query string
* @param none
*/
function present_reservation($resid) {
	global $Class;

	// Get info about this reservation
	$res = new $Class($resid, false, false, $_GET['scheduleid']);
	// Load the properties
	if ($resid == null) {
		$res->resource = new Resource($_GET['machid']);
		$res->start_date = $_GET['start_date'];
		$res->end_date = $_GET['start_date'];
		$res->user = new User(Auth::getCurrentID());
		$res->is_pending = $_GET['pending'];
		$res->start = $_GET['starttime'];
		$res->end = $_GET['endtime'];
	}

	$cur_user = new User(Auth::getCurrentID());
	$res->adminMode = Auth::isAdmin() || $cur_user->get_isadmin() || $cur_user->is_group_admin($res->user->get_groupids() );
	
	if (Auth::isAdmin() || $cur_user->get_isadmin())
	{
		$res->is_pending = false;	
	}
	
	$res->set_type($_GET['type']);
	$res->print_res();
}


/**
* Return array of data from query string about this reservation
*  or about a new reservation being created
* @param none
*/
function getResInfo() {
	$res_info = array();
	global $Class;

	// Determine title and set needed variables
	$res_info['type'] = $_GET['type'];
	switch($res_info['type']) {
		case RES_TYPE_ADD :
			$res_info['title'] = "New $Class";
			$res_info['resid']	= null;
			break;
		case RES_TYPE_MODIFY :
			$res_info['title'] = "Modify $Class";
			$res_info['resid'] = $_GET['resid'];
			break;
		case RES_TYPE_DELETE :
			$res_info['title'] = "Delete $Class";
			$res_info['resid'] = $_GET['resid'];
			break;
        case RES_TYPE_APPROVE :
			$res_info['title'] = "Approve $Class";
			$res_info['resid'] = $_GET['resid'];
			break;
        default : $res_info['title'] = "View $Class";
			$res_info['resid'] = $_GET['resid'];
			break;
	}

	return $res_info;
}
?>
